<template>
  <div ref="container" style="padding-bottom: 18vw;" :loading="loading">
    <div v-if="!isError && !isSubmited" class="bottomTool" style="display: flex;align-items: center;flex-wrap: nowrap;justify-content: space-around;">
      <van-button block round plain color="#24bfa0" :disabled="jhpjSN==0" size="small" style="margin-top:0" @click="prev">
        上一位
      </van-button>
      <van-button block round plain color="#24bfa0" :disabled="jhpjSN==(allTeacher.length-1)" size="small" style="margin-top:0" @click="next">
        下一位
      </van-button>
      <van-button block round color="#24bfa0" :disabled="!isCanEditAnswer" size="small" style="margin-top:0" @click="submit">
        {{isFinish?'重新提交':'提交'}}
      </van-button>
    </div>
    <!-- <h2 v-if="!isSubmited" class="van-block__title">
      {{ title }}
    </h2> -->
    <van-sticky>
      <div class="head">
        <van-icon name="arrow-left" class="plan-nav__back" @click="back" />
        <div class="title">
          {{ nowTeacher.user_name+'('+nowTeacher.label_title+')' }}
        </div>
      </div>
    </van-sticky>
    <div v-if="!isError && !isSubmited" style="padding-bottom:30px">
      <!-- {{question[0]}} -->
      <div v-for="(item, index) in question" :key="'t' + index" class="questionWrap">
        <!-- // 单选 -->
        <div v-if="item.parent == ''" :class="{ 'required': item.is_required,title:true }"> 
          <van-tag plain type="primary">
            {{ allType[item.type] }}
          </van-tag>
          {{ (index+1)>9?(index+1):'0'+(index+1) }}.{{ item.question_title }}?
        </div>
        <div v-if="(item.type == 1 || item.type == 2) &&item.parent == ''" class="tip">
          {{ item.description }}
        </div>
        <div v-if="item.parent == ''" class="imgWrap">
          <van-image v-for="(it,index) in item.pic" :key="index"
                     width="90px"
                     height="90px"
                     fit="cover"
                     :src="it"
                     @click="imgView(item.pic,index)"
          />
        </div>
        <van-radio-group v-if="item.type == 1 && item.parent == ''" v-model="item.answer" @change="dealCheckbox($event, item)">
          <van-radio v-for=" (it, index) in item.option_json" :key="index" :name="it.questionOptionId" shape="square">
            {{ allSN[index] +'.'+ it.name }}
          </van-radio>
        </van-radio-group>
        <van-checkbox-group v-if="item.type == 2 && item.parent == ''" v-model="item.answer" :max="item.limit_max" @change="dealCheckbox($event, item)">
          <van-checkbox v-for=" (it, index) in item.option_json" :key="index" :name="it.questionOptionId" shape="square">
            {{ allSN[index] +'.'+ it.name }}
          </van-checkbox>
        </van-checkbox-group>
        <van-field v-if="item.type == 3 && item.parent == ''&& item.is_score==0" :key="'text' + index" v-model="item.answer"
                   :placeholder="item.description" rows="2" autosize type="textarea" :maxlength="item.limit_max"
                   show-word-limit @input="checkString(item.answer, item)"
        ></van-field>
        <van-field v-if="item.type == 3 && item.parent == ''&& item.is_score==1" :key="'text' + index" name="slider">
          <template #input>
            <van-slider v-model="item.answer" :min="item.limit_min" :max="item.limit_max" @change="onChange($event,item)"/>
          </template>
        </van-field>
        <div v-if="item.type == 3 && item.parent == ''&& item.is_score==1" style="padding: 10px 0;">{{ item.answer }}分</div>
        <div v-if="item.type == 2 && item.parent == ''&& item.is_score==0" style="padding: 10px 0;color:#455a6499;font-size: 12px;"><van-icon name="info-o" /> 多选题最多选择{{ item.limit_max }}项</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Row, Col, Icon, Cell, CellGroup, Tag, Toast } from 'vant';
import { CountDown, Field, Image as VanImage, ImagePreview, Tab, Tabs, RadioGroup, Radio, Checkbox, CheckboxGroup, Button, Sticky, Uploader, Empty, Dialog, NumberKeyboard,Slider} from 'vant';
import { Popup, Picker, DatetimePicker, Calendar } from 'vant';
// import wechat from '../../util/wechat';
// import wx from "weixin-js-sdk";
import errorImg from "../../assets/img/error.jpg";
import okImg from "../../assets/img/ok.jpg";
// import { all } from 'core-js/fn/promise';

// import uploadWxImage from '../../util/imgUp/upload'
export default {
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [Tag.name]: Tag,
    [CellGroup.name]: CellGroup,
    [CountDown.name]: CountDown,
    [Icon.name]: Icon,
    [Toast.name]: Toast,
    [Field.name]: Field,
    [VanImage.name]: VanImage,
    [ImagePreview.name]: ImagePreview,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Button.name]: Button,
    [Sticky.name]: Sticky,
    [Uploader.name]: Uploader,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Calendar.name]: Calendar,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Dialog.name]: Dialog,
    [Slider.name]: Slider,
    [Dialog.Component.name]: Dialog.Component,
    [NumberKeyboard.name]: NumberKeyboard,
    [Empty.name]: Empty
  },
  data() {
    return {
      planInfo: null,
      errorImg: errorImg,
      okImg: okImg,
      question: [],
      allTeacher: [],
      // 老师序号第几名
      jhpjSN:0,
      nowTeacher:{
        user_name:'',
        label_title:'',
      },
      loading: false,
      //当前查看的日期
      activeName: null,
      diningInfoDialog: false,
      allAnswerData: null,
      isSubmited:false,
      isError:false,
      allSN: {},
      // 当前计划的modelID
      model_id:'',
      // 计划是否开启二次编辑是否已提交 后台判断
      isCanEditAnswer:true,
      // 数字键盘
      numberShow:false,
      number:'',
      numberObj:{},
      allType:{1:'单',2:"多",3:'问'},
      isFinish:false
    };
  },
  watch: {
    //监听从props里拿到值了
    number() {
      this.numberObj.answer=this.number
    },
  },
  created() {
    // if (sessionStorage.isSubmited !== undefined) {
    //   this.isSubmited = sessionStorage.isSubmited
    // }
  }, beforeDestroy() {
    //localStorage.removeItem('tempData')
    //Toast.fail('缓存已过期从新返回进入');
  }, mounted() {

    //  生成26个字母
    for (let i=0; i<26; i++) {
      // 输出A-Z  26个大写字母
      this.allSN[i]=String.fromCharCode(65 + i)
    }
     
    // 当前查看的教师序号（上一条 下一条）
    this.jhpjSN=Number(sessionStorage.jhpjSN) || this.$route.query.index
    //缓存计划信息及老师信息
    this.planInfo = JSON.parse(sessionStorage.zhpjtPlanInfo)
    this.allTeacher = JSON.parse(sessionStorage.zhpjQList)
    this.nowTeacher=this.allTeacher[this.jhpjSN]
    // var promise = new Promise((resolve, reject) => {
    //   wechat(function () {
    //     resolve(1)
    //   })

    // });
    // promise.then((data) => {

    //获取计划提交详情
    this.getDetail();
  
  }, methods: {
    onChange(value,question) {
      // Toast('当前值：' + value);
      question.answer=Math.floor(value)
    },
    // 图片预览
    imgView (item, index) {
      ImagePreview({
        images: item,
        startPosition: index
      });
    },
    prev(){
      this.jhpjSN = Number(this.jhpjSN) -1; // 修正这里
      sessionStorage.jhpjSN = this.jhpjSN;
      this.nowTeacher = this.allTeacher[this.jhpjSN];
      this.getDetail();
    },
    next(){
      this.jhpjSN = Number(this.jhpjSN) + 1; // 修正这里
      sessionStorage.jhpjSN = this.jhpjSN;
      this.nowTeacher = this.allTeacher[this.jhpjSN];
      this.getDetail();
    },
    // 显示键盘
    numberjpShow(obj){
      this.numberObj=obj
      this.number=obj.answer
      this.numberShow = true
    },
    // 隐藏键盘
    numberDeal(obj){
      this.numberObj.answer=this.number
      this.numberShow = false
    },
    dealCheckbox(value, question) {
      //所有的关联都隐藏 2024年12月6日 09:09:50
      question.child.map(item => {
        const showQuestion = this.idAdd(item.toString())
        const dealObj=(this.question[showQuestion[0] - 1])
        //被关联且不是答案的隐藏
        dealObj.parent = item//item.id
        if (dealObj.child) {
          dealObj.child.map(it => {
            const showCQuestion = this.idAdd(it.toString())
            const dealCObj=(this.question[showCQuestion[0] - 1])
            //被关联且不是答案的隐藏
            dealCObj.parent = it
            
          })
        }
      })
      this.question.forEach(it => {
        if(it.option_json.length>0 ){
          it.option_json.map(item => {
            if (item.related !== '' && (Array.isArray(it.answer)&&it.answer.includes(item.questionOptionId)||value===item.questionOptionId)) {
              item.related.split(',').map(ite => {
                const showQuestion = this.idAdd(ite.toString())
                //被关联且不是答案的隐藏
                this.question[showQuestion[0] - 1].parent = it.parent===''?'':this.question[showQuestion[0] - 1].question_id
              })
            }
          })
        }
      })
      // console.log(this.question)
    },
    //   /**
    //  * 阻止模态框关闭
    //  * @description 根据操作判断
    //  * @param {String} action - 是确定还是取消
    //  * @param {Function} done - 操作函数
    //  * @return Function
    //  */
    //   onBeforeClose(action, done) {
    //     // 点击了确定按钮
    //     if (action === "confirm") {
    //       // if()...也可以加入一些条件
    //       return done(false);//直接return它即可阻止
    //     }
    //     // 点击了取消按钮
    //     else {
    //       done(true); //关闭弹窗, true可以省略
    //     }
    //   },
    //时间转年月日格式(年-月-日格式)
    renderTimeStr(date){
      return date?new Date(date).toJSON().substr(0,10):new Date().toJSON().substr(0,10)
    },
    // 禁止输入表情
    checkString(value, obj) {
      const dealValue = value.replace(/(^\s*)|(\s*$)/g, "")
      if (dealValue === '') {
        obj.answer = ''
      } else {
        const saveAnswer=value.replace(/[^\u4E00-\u9FA5|\d|a-zA-Z|\r\n\s,.?!，。？！…—&$=()-+/*{}[\]]|\s/g, '')
        if(obj.is_score){
          obj.answer = value.replace(/[^\d]/g, '')
        }else{
          obj.answer = saveAnswer
        }
      }
    },
    //正数
    checkNumber(value, obj) {
      const dealValue = ("" + value).replace(/[^\d^\\.]+/g, "").replace(/^0+(\d)/, "$1").replace(/^\./, "0.").match(/^\d*(\.?\d{0,2})/g)[0] || ""
      obj.answer = dealValue > 24 ? '24' : dealValue
    },
    // 查询当前id 所在位置
    idAdd(ids) {
      const nowADD = []
      const allIds=ids.split(',').map(Number)
      this.question.map((item, index) => {
        if (allIds.includes(item.question_id)) {
          nowADD.push((index) + 1)
        }
      })
      return nowADD
    },
    // 获取题目
    async getDetail() {
      const _this=this
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        overlay: true,
      });
      const params={
        evaluator2evaluatedId:this.nowTeacher.evaluator2evaluated_id,
      }            
      const res = await this.$api.list.question.get(params);
      
      if (res.code === 200) {
        Toast.clear();
        this.isCanEditAnswer = res.data.isCanEditAnswer===1
        this.isFinish=res.data.isFinish===1
        this.model_id=res.data.model.id
        this.question = res.data.qaVoList.map((item, index) => {
          item.parent = ''
          if (item.type === 3) {
            item.answer = item.answer==null?'':item.answer
            item.limit_max=item.limit_max.toString()
            item.limit_min=item.limit_min.toString()
            item.option_json=[]
            if(item.answer===''&& item.is_score===1){
              item.answer=item.limit_min
            }
          }
          if ( item.type === 1) {
            item.answer = item.answer==null || item.answer ===''?'':Number(item.answer)
          }
          if (item.type === 2) {
            item.answer = item.answer==null || item.answer ===''?[]:Array.from(new Set(item.answer.split(','))).map(Number)
          }
          if (item.type === 2 || item.type === 1) {
            item.option_json = item.option_json === '' ? [] : JSON.parse(item.option_json)
            item.child = []
            const defaultAnswer=[]
            item.option_json.map(it => {
              if(it.checked){
                if (item.type === 2 ) {
                  if(item.answer.length===0){
                    defaultAnswer.push(it.questionOptionId)
                  }
                }else{
                  if(item.answer ===''){
                    item.answer=it.questionOptionId
                  }
                  
                }
              }

             

              //关联项整理
              if (it.related !== '' && it.related !== undefined) {
                it.related.split(',').map(ite => {
                  item.child.push(ite)
                  this.$nextTick(() => {
                    const showQuestion = this.idAdd(ite.toString())
                    if (showQuestion.length > 0) {
                      if(item.type === 2 && item.child.includes(ite) && item.answer.includes(it.questionOptionId)){
                        this.question[showQuestion[0] - 1].parent = ''
                      }else{
                        this.question[showQuestion[0] - 1].parent = item.id
                      }
                      if(item.type !== 2){
                        this.question[showQuestion[0] - 1].parent = item.id
                      }
                    }
                  })
                })
              }
            })

            if(item.answer.length===0 && item.type === 2){
              item.answer=defaultAnswer
            }
          }
          item.pic=item.pic==null||item.pic===''?[]:JSON.parse(item.pic).map(item => item.url)
          item.is_required = item.is_required === 1

          const handleDealCheckbox = (item) => {
            if (item.parent === '') {
              this.$nextTick(() => {
                setTimeout(() => {
                  _this.dealCheckbox(item.answer, item);
                }, 100);
              });
            }
          };
          try {
            if (item.type === 2 || item.type === 1) {
              handleDealCheckbox(item);
            }
          } catch (error) {
            console.error('处理checkbox时出错:', error);
            Toast.fail('处理过程中发生错误，请稍后再试！');
          }

          return item
        })
        console.log(this.question)
      } else {
        Toast.fail(res.message);
      }
    },
    
    //-----------------------------------------------------------------------------------------------------------------------------------------
    objToParams(obj) {
      const arr = [];
      for (const key in obj) {
        arr.push(`${key}=${obj[key]}`);
      }
      return arr.join('&');
    },
    back() {
      window.history.back()
    },
    // 提交
    async submit() {
      // 遍历必填
      const emptyArray=[]
      const answerArray=[]
      const errorArray=[]

      this.question.forEach((item, index) => {
        const isRequired = item.is_required;
        const isParentEmpty = item.parent === '';
        const isAnswerEmpty = item.answer === '' || (Array.isArray(item.answer) && item.answer.length === 0);

        if (isRequired && isAnswerEmpty && isParentEmpty) {
          emptyArray.push(index + 1);
        }
        if (isParentEmpty) {
          if (item.type !== 2 && !isAnswerEmpty) {
            answerArray.push({
              questionId: item.question_id,
              answer: item.answer
            });
          } else if (item.type === 2) {
            if (item.answer.length < item.limit_min) {
              errorArray.push(`第${index + 1}题至少选择${item.limit_min}项!`);
            }
            answerArray.push({
              questionId: item.question_id,
              answer: item.answer.join(',')
            });
          }
        }
      });

      // 错误处理机制
      if (emptyArray.length > 0) {
        console.error(`必填项未填写: ${emptyArray.join(', ')}`);
        Dialog.alert({
          title: '提示',
          message: '第'+emptyArray.join(',')+'为必填项未填写!',
        }).then(() => {
        // on close
        });
        return false
      }

      if (errorArray.length > 0) {
        console.error(`错误提示: ${errorArray.join(', ')}`);  
        Dialog.alert({
          title: '提示',
          message: errorArray.join(','),
        }).then(() => {
        // on close
        });
        return false
      }

      Toast.loading({
        forbidClick: true,
        overlay: true,
      });

      const params={
        evaluator2evaluatedId:this.nowTeacher.evaluator2evaluated_id,
        planId:this.planInfo.id,
        modelId:this.model_id,
        answerJson:JSON.stringify(answerArray)
      }
      const res = await this.$api.list.submit.post(params);
      Toast.clear()
      if (res.code === 200) {
        Dialog.alert({
          message: '提交成功',
        }).then(() => {
        // on close
        });
      } else {
        Toast.fail(res.message);
      }

    }
  }
};
</script>

<style lang="less" scoped>
@bzcolor: #24bfa0;
.van-dialog__confirm, .van-dialog__confirm:active{
  color: @bzcolor;
}
::v-deep .van-tag--questionType {
  //background-color: @bzcolor;
  padding: 2px 4px;
  margin-top: 1vw;
  margin-right: 2vw;
  color: red;
}

::v-deep .custom-title {
  font-weight: bold;
  margin-top: 0.6vw;
  font-size: 3.6vw;
}

// ::v-deep .van-cell::after {
//     border-bottom: none;
// }

::v-deep .van-cell__title {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}
// ::v-deep .van-cell-group {
//   margin: 3vw 0;
//   padding-top: 5px;
// }

// ::v-deep .van-field {
//   background: #f4f5f7;
//   border-radius: 1vw;
// }

::v-deep .questionDescription {
  margin-bottom: 3vw;
}

::v-deep .questionPic {
  padding-bottom: 3vw;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: flex-start;
  justify-content: flex-start;
  flex-wrap: wrap;
}

// ::v-deep .van-radio,
// .van-checkbox {
//   margin-bottom: 3vw;
// }

::v-deep .van-radio__icon--checked .van-icon,
.van-checkbox__icon--checked .van-icon {
  background-color: @bzcolor;
  border-color: @bzcolor;
}

::v-deep .bottomTool {
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 99;
  top: auto;
  position: fixed;
  padding: 3vw;
  background: #fff;
  box-shadow: 0px -3px 6px 0px #efeeeecc;
  button {
    max-width: 24vw;
  }
}

::v-deep .oneQuestionWrap {
  padding: 0px 20px 24px 10vw;
  display: flow-root;
}

::v-deep .errorTip {
  font-weight: bold;
  padding-top: 2vw;
}

// ::v-deep button+button {
//   margin-top: 3vw;
//   color: #8f8f8f;
//   border-color: #dddee0;
// }

::v-deep .van-button--primary {
  color: #fff;
  background-color: #06c09b;
  border: 1px px solid #06c09b;
}

::v-deep .van-checkbox__icon--checked .van-icon {
  color: #fff;
  background-color: #06c09b;
  border-color: #06c09b;
}

::v-deep .van-empty__image {
  width: 200px;
  height: auto;
}

// ::v-deep .van-field__control {
//   padding-right: 5px;
//   min-height: 148px;
// }
.imgWrap {
  padding: 1px 0 16px 0;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: row;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: flex-start;
  box-sizing: border-box;
  flex-wrap: wrap;
}
.van-image {
    margin: 2px;
}
/* // ::v-deep .van-uploader__wrapper .van-uploader__upload {
    //   display: none;
    // } */
::v-deep .van-uploader__upload1 {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  box-sizing: border-box;
  width: 72px;
  height: 72px;
  margin: 0 8px 8px 0;
  background-color: #f7f8fa;

  input {
    display: none;
  }
}

::v-deep .van-uploader__input {
  display: none;
}

::v-deep div,
.van-cell {
  word-break: break-all;
}

::v-deep .storageBtn {
  color: #fdfdfd;
  background: #07c160;
  border-color: #a6e6e6;
}

.van-block__title {
  margin: 0;
  padding: 22px 16px 10px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
}

.van-field__button {
  color: #ef7907;
  background: #f5f5f5;
  padding: 0 4px;
  margin-left: 10px;
  font-weight: bold;
}

.van-cell.required::before {
  content: '*';
  color: red;
  position: absolute;
  left: 1.6vw;
  top: 3.1vw;
}

.van-field__control--right {
  margin-right: 10px;
}

::v-deep .van-dialog__confirm,
.van-dialog__confirm:active {
  color: #07c160;
}

.van-uploader__preview-image {
  width: 72px;
  height: 72px;
}

// 新增   2024年7月24日13:59:00 
.setDiningTitle {
  padding: 10px 16px 8px 10px;
  font-size: 14px;
  font-weight: bold;
}

.diningTitle {
  margin: 0;
  padding: 10px 16px 6px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
  line-height: 16px;
}

// ::v-deep .van-tab {
//     -webkit-box-pack: start;
//     -ms-flex-pack: start;
//     justify-content: flex-start;
// }

.confirmInfo {
  .diningTag {
    margin-right: 5px;

    .red {
      color: #f30
    }
    .green {
      color: #24bfa0
    }
  }
  .van-cell__title {
    flex-direction: column;
  }
}
.confirmBtn {
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-shrink: 0;
  flex-shrink: 0;
  padding: 8px 16px;

  .van-button:first-of-type {
    border-top-left-radius: 20px;
    border-bottom-left-radius: 20px;
    width: 150%;
  }

  .van-button:last-of-type {
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
    width: 100%;
  }
}

.noData {
  background: #fff7ef;
    padding: 6px 17px;
    font-size: 14px;
    color: #cd7521;
    line-height: 31px;
}
::v-deep .van-radio__icon .van-icon {
  border-radius: 50%;
}

.questionWrap{
  padding: 0 16px 0 20px;
  position: relative;
  font-size: 14px;
  .title {
    padding: 10px 0 10px 0;
    line-height: 26px;
    .van-tag {
      margin-right: 2px;
      color: #79b1ea;
      padding-top: 2px;
    }
  }
  .tip {
  color: #7f95ab;
  padding: 0 0 12px;
}
  .required::before {
  content: '*';
  color: red;
  position: absolute;
  left: 2.4vw;
  top: 3.1vw;
}
.van-radio__icon .van-icon {
  border-radius: 40%;
}
.van-radio,.van-checkbox {
  padding-bottom: 10px;
}
}
.head {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  height: 44px;
  background-color: #fff;
  margin-bottom: 10px;
  .title {
    font-weight: 600;
    font-size: 16px;
    text-transform: capitalize;
    overflow: hidden; /* 确保超出容器的文本被裁剪 */
    white-space: nowrap; /* 防止文本换行 */
    text-overflow: ellipsis; /* 在文本超出容器宽度时显示省略号 */
    max-width: 80%;
  }
  .plan-nav__back {
    position: absolute;
    top: 15px;
    left: 16px;
    width: 24px;
    font-size: 20px;
    height: 24px;
    cursor: pointer;
}
 }
</style>